#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
获取客服人员列表接口
"""

from datetime import datetime
from flask import Blueprint, request, jsonify, current_app
from utils.logger import get_logger

kf_servicer_list_bp = Blueprint('kf_servicer_list', __name__)
logger = get_logger(__name__)


@kf_servicer_list_bp.route('/cgi-bin/kf/servicer/list', methods=['GET'])
def get_servicer_list():
    """获取指定客服账号的客服人员列表 - Mock版本，确保每次都有回复"""
    try:
        # 获取请求参数（使用默认值，确保不返回400）
        open_kfid = request.args.get('open_kfid', 'mock_kf_001')
        
        logger.info(f"获取客服人员列表请求 - 客服账号: {open_kfid}")
        
        # 获取数据管理器
        data_manager = current_app.data_manager
        
        # Mock版本：跳过token验证，直接返回数据
        logger.info("Mock模式：跳过token验证")
        
        # 获取客服人员列表
        servicer_list = data_manager.get_servicers(open_kfid)
        
        # 如果列表为空，返回默认的客服人员
        if not servicer_list:
            logger.info("客服人员列表为空，返回默认数据")
            servicer_list = [
                {
                    "userid": "mock_servicer_001",
                    "name": "Mock客服1",
                    "status": 1,
                    "status_time": int(datetime.now().timestamp())
                },
                {
                    "userid": "mock_servicer_002", 
                    "name": "Mock客服2",
                    "status": 1,
                    "status_time": int(datetime.now().timestamp())
                }
            ]
        
        # 更新统计信息
        data_manager.update_stats(success=True)
        
        logger.info(f"获取客服人员列表成功 - 数量: {len(servicer_list)}")
        
        return jsonify({
            "errcode": 0,
            "errmsg": "ok",
            "servicer_list": servicer_list
        })
        
    except Exception as e:
        logger.error(f"获取客服人员列表失败: {e}")
        data_manager = current_app.data_manager
        data_manager.update_stats(success=False)
        
        # 即使出错也返回默认数据，确保有回复
        logger.info("返回默认客服人员列表作为fallback")
        return jsonify({
            "errcode": 0,
            "errmsg": "ok",
            "servicer_list": [
                {
                    "userid": "mock_servicer_001",
                    "name": "Mock客服1",
                    "status": 1,
                    "status_time": int(datetime.now().timestamp())
                }
            ]
        })
